<?php

namespace app\common\service\driver;

use think\Exception;

/**
 * 阿里云OSS存储驱动
 */
class AliyunOSSDriver
{
    protected $config;
    protected $ossClient;

    public function __construct($config)
    {
        $this->config = $config;
        $this->initOSSClient();
    }

    /**
     * 初始化OSS客户端
     */
    protected function initOSSClient()
    {
        $configData = $this->config->config;
        
        if (empty($configData['access_key_id']) || empty($configData['access_key_secret'])) {
            throw new Exception('阿里云OSS配置不完整：缺少AccessKey');
        }
        
        if (empty($configData['endpoint']) || empty($configData['bucket'])) {
            throw new Exception('阿里云OSS配置不完整：缺少Endpoint或Bucket');
        }
        
        // 这里需要引入阿里云OSS SDK
        // 实际使用时需要安装：composer require aliyuncs/oss-sdk-php
        try {
            $this->ossClient = new \OSS\OssClient(
                $configData['access_key_id'],
                $configData['access_key_secret'],
                $configData['endpoint']
            );
        } catch (\OSS\Core\OssException $e) {
            throw new Exception('阿里云OSS连接失败：' . $e->getMessage());
        }
    }

    /**
     * 上传文件
     */
    public function upload($file, $fileInfo)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        $object = $fileInfo['file_path'];
        
        try {
            $result = $this->ossClient->uploadFile($bucket, $object, $file->getRealPath());
            
            // 生成访问URL
            $domain = $configData['domain'] ?? '';
            if ($domain) {
                $fileUrl = rtrim($domain, '/') . '/' . $object;
            } else {
                $fileUrl = $this->ossClient->signUrl($bucket, $object, 3600);
            }
            
            return [
                'file_path' => $fileInfo['file_path'],
                'file_url' => $fileUrl
            ];
        } catch (\Exception $e) {
            throw new Exception('阿里云OSS上传失败：' . $e->getMessage());
        }
    }

    /**
     * 删除文件
     */
    public function delete($filePath)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        
        try {
            $this->ossClient->deleteObject($bucket, $filePath);
            
            return true;
        } catch (\Exception $e) {
            throw new Exception('阿里云OSS删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文件URL
     */
    public function getUrl($filePath)
    {
        $configData = $this->config->config;
        $domain = $configData['domain'] ?? '';
        
        if ($domain) {
            return rtrim($domain, '/') . '/' . $filePath;
        } else {
            // 生成临时访问URL
            return $this->ossClient->signUrl($configData['bucket'], $filePath, 3600);
        }
    }

    /**
     * 检查文件是否存在
     */
    public function exists($filePath)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        
        try {
            return $this->ossClient->doesObjectExist($bucket, $filePath);
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 测试连接
     */
    public function test()
    {
        try {
            $this->ossClient->listObjects($this->config->config['bucket'], ['max-keys' => 1]);
            
            return true;
        } catch (\Exception $e) {
            throw new Exception('阿里云OSS连接测试失败：' . $e->getMessage());
        }
    }
}
